/**
 * Copyright (c) 2006 RiseSoft Co.,Ltd  
 * $Header$
 */
package net.risesoft.risebi.collection.web.admin;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import net.risesoft.risebi.collection.commons.constants.SystemConstants;
import net.risesoft.risebi.collection.event.eventobj.EventObject;
import net.risesoft.risebi.collection.event.eventobj.SystemLogEventObj;
import net.risesoft.risebi.collection.filesync.FileSyncReceiver;
import net.risesoft.risebi.collection.model.Application;
import net.risesoft.risebi.collection.model.Catalog;
import net.risesoft.risebi.collection.model.Monitor;
import net.risesoft.risebi.collection.model.Service;
import net.risesoft.risebi.collection.model.SoCollection;
import net.risesoft.risebi.collection.model.Speciality;
import net.risesoft.risebi.collection.model.StatisticalObjectTree;
import net.risesoft.risebi.collection.model.SystemLog;
import net.risesoft.risebi.collection.model.User;
import net.risesoft.risebi.collection.service.ApplicationManager;
import net.risesoft.risebi.collection.service.CatalogManager;
import net.risesoft.risebi.collection.service.ServiceManager;
import net.risesoft.risebi.collection.service.SoCollectionManager;
import net.risesoft.risebi.collection.service.SpecialityManager;
import net.risesoft.risebi.collection.service.StatisticalObjectTreeManager;
import net.risesoft.risebi.collection.web.BaseAction;
import net.risesoft.risebi.collection.wsmonitor.MonitorService;
import net.risesoft.risebi.commons.struts2extension.Trimable;
import net.risesoft.risebi.commons.util.ContextUtil;
import net.risesoft.risebi.commons.util.ExceptionUtil;
import net.risesoft.risebi.commons.util.GUID;
import net.risesoft.risebi.commons.util.JSONUtil;
import net.risesoft.risebi.commons.util.PropsUtil;
import net.sf.json.JSONObject;

import org.apache.commons.beanutils.LazyDynaBean;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.cxf.frontend.ClientProxyFactoryBean;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Namespace;
import org.apache.struts2.convention.annotation.Result;

import com.opensymphony.xwork2.ActionInvocation;

/**
 * 应用管理action
 *
 * @author <a href="mailto: dingzhaojun@risesoft.net">dingzhaojun</a>
 * @version $Revision$
 * 
 */
@Namespace("/admin/ApplicationAction")
public class ApplicationAction extends BaseAction implements Trimable {
	
	private static final long serialVersionUID = 5784509154060429178L;
	private static Log log = LogFactory.getLog(ApplicationAction.class);
	
	private SpecialityManager specialityManager;
	private ApplicationManager applicationManager;
	private StatisticalObjectTreeManager statisticalObjectTreeManager;
	private SoCollectionManager soCollectionManager;
	private ServiceManager serviceManager;
	private CatalogManager catalogManager;
	private String json_services;	
	private String json_specialities;
	private String json_specialities_filter;
	private String json_soTrees;
	private String currentServiceGuid;
	
	private Application appObj;
	
	@Action(value="prepareAppList",
			results={@Result(name="success", location="/admin/application/appList.jsp")}
	)
	public String prepareAppList() throws Exception {
		this.currentServiceGuid = this.getDefaultService().getGuid();
		
		List<Service> lst1 = serviceManager.getObjects(Service.class);
		this.json_services = JSONUtil.getJsonString("include","guid,name",lst1);
		
		List<Speciality> lst2 = specialityManager.find("from Speciality s where s.service.guid='" + this.currentServiceGuid + "'");
		this.json_specialities = JSONUtil.getJsonString("include","guid,chineseName",lst2);
		
		List<Speciality> lst3 = specialityManager.find("from Speciality s where s.service.guid='" + this.currentServiceGuid + "'");
		ArrayList al = new ArrayList();			
		LazyDynaBean ldb = new LazyDynaBean();
		ldb.set("guid", "");
		ldb.set("chineseName", "[全部]");
		al.add(ldb);
		
		for(Speciality t : lst3){
			ldb = new LazyDynaBean();
			ldb.set("guid", t.getGuid());
			ldb.set("chineseName", t.getChineseName());
			al.add(ldb);
		}
		this.json_specialities_filter = JSONUtil.getJsonString("include","guid,chineseName",al);
		
		List<StatisticalObjectTree> lst4 = statisticalObjectTreeManager.getObjects(StatisticalObjectTree.class);
		this.json_soTrees = JSONUtil.getJsonString("include","appGuid,guid,name",lst4);

		return SUCCESS;
	}

	@Action(value="prepareSelectApplication",
		results={@Result(name="success", location="/admin/application/selectApplication.jsp")}
	)
	public String prepareSelectApplication() throws Exception {
		if(this.node==null || this.node.length()==0){
			this.currentServiceGuid = this.getDefaultService().getGuid();
		}else{
			this.currentServiceGuid = this.node;
		}
		
		List<Speciality> lst = specialityManager.find("from Speciality s where s.service.guid='" + this.currentServiceGuid + "'");
		ArrayList al = new ArrayList();			
		LazyDynaBean ldb = new LazyDynaBean();
		ldb.set("guid", "");
		ldb.set("chineseName", "[全部]");
		al.add(ldb);
		
		for(Speciality t : lst){
			ldb = new LazyDynaBean();
			ldb.set("guid", t.getGuid());
			ldb.set("chineseName", t.getChineseName());
			al.add(ldb);
		}
		this.json_specialities = JSONUtil.getJsonString("include","guid,chineseName",al);
		
		return SUCCESS;
	}

	/**
	 * @see net.risesoft.commons.struts2extension.Trimable#afterTrim(com.opensymphony.xwork2.ActionInvocation)
	 */
	public void afterTrim(ActionInvocation invocation) {
		
	}

	/**
	 * @see net.risesoft.commons.struts2extension.Trimable#preTrim(com.opensymphony.xwork2.ActionInvocation)
	 */
	public boolean preTrim(ActionInvocation invocation) {
		return true;
	}
	
	@Action(value="refreshJson")
	public String refreshJson() throws Exception {
		try{
			if("jsonList".equalsIgnoreCase(this.whichJson)){
				if(this.appObj==null){
					this.appObj = new Application();
				}
				
				this.appObj.setServiceGuid(this.getDefaultService().getGuid());
				Map map = applicationManager.getPagedAppsByServiceWithPermission(this.appObj, this.getSessionUser(),this.start,this.limit);
				
				this.json = JSONUtil.getJsonString("include","count,list,serviceGuid,specialityGuid,soTreeGuid,guid,name,chineseName,description,status,userType,type,inner,tabIndex",map);
			}else if("jsonSelectAppList".equalsIgnoreCase(this.whichJson)){
				if(this.appObj==null){
					this.appObj = new Application();
				}
				if(this.currentServiceGuid==null || this.currentServiceGuid.length()==0){
					this.currentServiceGuid = this.getDefaultService().getGuid();
				}
				this.appObj.setServiceGuid(this.currentServiceGuid);
				Map map = applicationManager.getPagedAppsByServiceWithPermission(this.appObj, this.getSessionUser(),this.start,this.limit);
				
				this.json = JSONUtil.getJsonString("include","count,list,specialityGuid,guid,name,chineseName,status,userType,type,inner,tabIndex",map);				
			}else if("jsonSoTables".equalsIgnoreCase(this.whichJson)){
				ArrayList al = new ArrayList();	
				
				LazyDynaBean ldb = new LazyDynaBean();
				ldb.set("text", "<<创建调查对象>>");
				ldb.set("menuType", "<<创建调查对象>>");
				ldb.set("cls", "x-btn-text-icon");
				if(this.getContextPath().endsWith("/")){
					ldb.set("icon", this.getContextPath()+"images/system/fam/add.png");
				}else{
					ldb.set("icon", this.getContextPath()+"/images/system/fam/add.png");
				}
				al.add(ldb);
				
				List<Catalog> lst = catalogManager.find("from Catalog t where t.type=1 and t.application.guid='" + this.node + "'");				
				for(Catalog t : lst){
					ldb = new LazyDynaBean();
					ldb.set("catalog_guid", t.getGuid());
					ldb.set("menuType", "<<调查对象>>");
					if(t.getSoType()==null){
						ldb.set("text", "【***】" + t.getTableName());
					}else{
						ldb.set("text", "【" + t.getSoType().getName().trim() + "】" + t.getTableName());
					}
					ldb.set("cls", "x-btn-text-icon");
					if(this.getContextPath().endsWith("/")){
						ldb.set("icon", this.getContextPath()+"images/system/fam/database_table.png");
					}else{
						ldb.set("icon", this.getContextPath()+"/images/system/fam/database_table.png");
					}
					al.add(ldb);
				}
				this.json = JSONUtil.getJsonString(null, null, al);
			}else if("jsonSoCollections".equalsIgnoreCase(this.whichJson)){
				ArrayList al = new ArrayList();	
				
				LazyDynaBean ldb = new LazyDynaBean();
				ldb.set("text", "<<创建对象集合>>");
				ldb.set("menuType", "<<创建对象集合>>");
				ldb.set("cls", "x-btn-text-icon");
				if(this.getContextPath().endsWith("/")){
					ldb.set("icon", this.getContextPath()+"images/system/fam/add.png");
				}else{
					ldb.set("icon", this.getContextPath()+"/images/system/fam/add.png");
				}
				al.add(ldb);
				
				List<SoCollection> lst = soCollectionManager.find("from SoCollection t where t.application.guid='" + this.node + "'");				
				for(SoCollection t : lst){
					ldb = new LazyDynaBean();
					
					String type = "";
					switch(t.getType()){
					case 1:
						type = "对象实例";
						break;
					case 2:
						type = "查询语句";
						break;
					case 3:
						type = "管理路径";
						break;
					default:
						type = "****";
					}
					
					ldb.set("guid", t.getGuid());
					ldb.set("type", t.getType());
					
					if(t.getTreeGuid()==null){
						ldb.set("sotGuid", "");
					}else{
						ldb.set("sotGuid", t.getTreeGuid());
					}
					if(t.getQueryGuid()==null){
						ldb.set("queryGuid", "");
					}else{
						ldb.set("queryGuid", t.getQueryGuid());
					}	
					
					ldb.set("menuType", "<<对象集合>>");
					ldb.set("text", "【" + type + "】" + t.getName());
					ldb.set("cls", "x-btn-text-icon");
					if(this.getContextPath().endsWith("/")){
						ldb.set("icon", this.getContextPath()+"images/system/fam/database_table.png");
					}else{
						ldb.set("icon", this.getContextPath()+"/images/system/fam/database_table.png");
					}
					al.add(ldb);
				}
				this.json = JSONUtil.getJsonString(null, null, al);
			}else if("jsonSoTrees".equalsIgnoreCase(this.whichJson)){
				ArrayList al = new ArrayList();	
				
				LazyDynaBean ldb = new LazyDynaBean();
				ldb.set("text", "<<创建对象树>>");
				ldb.set("menuType", "<<创建对象树>>");
				ldb.set("cls", "x-btn-text-icon");
				if(this.getContextPath().endsWith("/")){
					ldb.set("icon", this.getContextPath()+"images/system/fam/add.png");
				}else{
					ldb.set("icon", this.getContextPath()+"/images/system/fam/add.png");
				}
				al.add(ldb);
				
				List<StatisticalObjectTree> lst = statisticalObjectTreeManager.find("from StatisticalObjectTree t where t.application.guid='" + this.node + "'");				
				for(StatisticalObjectTree t : lst){
					ldb = new LazyDynaBean();					
					ldb.set("guid", t.getGuid());
					ldb.set("text", t.getName());
					ldb.set("menuType", "<<对象树>>");
					ldb.set("cls", "x-btn-text-icon");
					if(this.getContextPath().endsWith("/")){
						ldb.set("icon", this.getContextPath()+"images/system/fam/database_table.png");
					}else{
						ldb.set("icon", this.getContextPath()+"/images/system/fam/database_table.png");
					}
					al.add(ldb);
				}
				this.json = JSONUtil.getJsonString(null, null, al);
			}else if("jsonSoTrees4appGuid".equalsIgnoreCase(this.whichJson)){
				ArrayList al = new ArrayList();					
				List<StatisticalObjectTree> lst = statisticalObjectTreeManager.find("from StatisticalObjectTree t where t.application.guid='" + this.node + "'");				
				for(StatisticalObjectTree t : lst){
					LazyDynaBean ldb = new LazyDynaBean();		
					ldb.set("guid", t.getGuid());
					ldb.set("name", t.getName());
					al.add(ldb);
				}
				this.json = JSONUtil.getJsonString(null, null, al);
			}else if("jsonPublishApplications".equalsIgnoreCase(this.whichJson)){
				List<Monitor> list = new ArrayList<Monitor>();
				
				String dataServer = PropsUtil.getProperty(SystemConstants.REPORT_DATASERVER);
				String[] dataServerColl = dataServer.split(",");
				
				for(String server:dataServerColl){
					String url = "http://" + server;
					if(!url.endsWith("/")){
						url += "/";
					}
					url += "ws/Monitor";
					
					Monitor monitor = new Monitor();
					monitor.setIp(server);
					monitor.setUrl(server);
					monitor.setType("数据管理服务器");
					monitor.setPublishStatus("0");
					try {
						ClientProxyFactoryBean factory = new ClientProxyFactoryBean();
						factory.setServiceClass(MonitorService.class);
						factory.setAddress(url);
						MonitorService client = (MonitorService) factory.create();
						
						client.ping();
						
						monitor.setConnected(true);
					} catch (Exception e) {
						monitor.setConnected(false);
					}
					list.add(monitor);
				}
				
				String clientServer = PropsUtil.getProperty(SystemConstants.REPORT_CLIENTSERVER);
				String[] clientServerColl = clientServer.split(",");
				
				for(String server:clientServerColl){
					String url = "http://" + server;
					if(!url.endsWith("/")){
						url += "/";
					}
					url += "ws/Monitor";
					
					Monitor monitor = new Monitor();
					monitor.setIp(server);
					monitor.setUrl(server);
					monitor.setType("企业填报服务器");
					monitor.setPublishStatus("0");
					try {
						ClientProxyFactoryBean factory = new ClientProxyFactoryBean();
						factory.setServiceClass(MonitorService.class);
						factory.setAddress(url);
						MonitorService client = (MonitorService) factory.create();
						
						client.ping();
						
						monitor.setConnected(true);
					} catch (Exception e) {
						monitor.setConnected(false);
					}
					list.add(monitor);
				}
				
				this.json = JSONUtil.getJsonString(null, null, list);
			}
		}catch(Exception e){
			this.json = "[]";
			e.printStackTrace();
		} 

		return AJAX;
	}

	@Action(value="insertOrUpdate")
	public String insertOrUpdate() throws Exception {
		User user = this.getSessionUser();
		
		LazyDynaBean ldb = new  LazyDynaBean();
		try{
			Application[] applicationList = (Application[])JSONUtil.stringToArray(this.json, Application.class);
			for (Application s : applicationList){
				boolean newed = false;
				if(s.getGuid()==null || s.getGuid().trim().length()==0 || s.getGuid().startsWith("NEW")){
					s.setGuid(new GUID().toString());
					newed = true;
				}
				//TODO:应该排重
				applicationManager.saveObject(s);
				
//        		记录日志
        		SystemLog systemLog = new SystemLog();
        		if(newed)
        			systemLog.setOpterateType(SystemLog.OPTERATETYPE_ADD);
        		else
        			systemLog.setOpterateType(SystemLog.OPTERATETYPE_EDIT);
        		systemLog.setUser(user);
        		
        		Service service = this.getDefaultService();
        		systemLog.setServiceGuid(service.getGuid());
        		
        		EventObject systemLogEventObject = new SystemLogEventObj(this);
        		Map systemLogMap = new HashMap();
        		systemLogMap.put("systemLog", systemLog);
        		if(newed)
        			systemLogMap.put("keyName", "applicationadd");
        		else
        			systemLogMap.put("keyName", "applicationedit");
        		systemLogMap.put("application", s);
        		
        		systemLogEventObject.setDataMap(systemLogMap);
        		ContextUtil.getAc().publishEvent(systemLogEventObject);
			}
			
			ldb.set("success", true);
			ldb.set("reason", "保存成功!");
			this.json = JSONObject.fromObject(ldb).toString();
		}catch(Exception e){
			log.error(ExceptionUtil.transformException(e));
			ldb.set("success", false);
			ldb.set("reason", e.getMessage());
			this.json = JSONObject.fromObject(ldb).toString();
		}

		return AJAX;
	}

	@Action(value="remove")
	public String remove() throws Exception {
		User user = this.getSessionUser();
		
		LazyDynaBean ldb = new  LazyDynaBean();
		try{
			Application application = (Application) applicationManager.getObject(Application.class, node);
			
			applicationManager.removeObject(Application.class, node);
			
//    		记录日志
    		SystemLog systemLog = new SystemLog();
    		systemLog.setOpterateType(SystemLog.OPTERATETYPE_REMOVE);
    		systemLog.setUser(user);
    		
    		Service service = this.getDefaultService();
    		systemLog.setServiceGuid(service.getGuid());
    		
    		EventObject systemLogEventObject = new SystemLogEventObj(this);
    		Map systemLogMap = new HashMap();
    		systemLogMap.put("systemLog", systemLog);
    		systemLogMap.put("keyName", "applicationremove");
    		systemLogMap.put("application", application);
    		
    		systemLogEventObject.setDataMap(systemLogMap);
    		ContextUtil.getAc().publishEvent(systemLogEventObject);
			
			ldb.set("success", true);
			ldb.set("reason", "删除成功!");
			this.json = JSONObject.fromObject(ldb).toString();
		}catch(Exception e){
			log.error(ExceptionUtil.transformException(e));
			ldb.set("success", false);
			ldb.set("reason", e.getMessage());
			this.json = JSONObject.fromObject(ldb).toString();
		}
		
		return AJAX;
	}
	
	@Action(value="preparePublishApplication",
			results={@Result(name="success", location="/admin/application/publishApplication.jsp")}
			)
	public String preparePublishApplication() throws Exception {
		return SUCCESS;
	}
	
	@Action(value="publishApplication")
	public String publishApplication() throws Exception {
		User user = this.getSessionUser();
		
		LazyDynaBean ldb = new  LazyDynaBean();
		try{
			String server = node;
			String url = "http://" + server;
			if(!url.endsWith("/")){
				url += "/";
			}
			url += "ws/FileSyncReceiver";
			
			String status = "0";
			try {
				ClientProxyFactoryBean factory = new ClientProxyFactoryBean();
				factory.setServiceClass(FileSyncReceiver.class);
				factory.setAddress(url);
				FileSyncReceiver client = (FileSyncReceiver) factory.create();
				
				client.receiveFileSyncMessage();
				
				status = "1";
				
//	    		记录日志
	    		SystemLog systemLog = new SystemLog();
	    		systemLog.setOpterateType(SystemLog.OPTERATETYPE_PROCESS);
	    		systemLog.setUser(user);
	    		
	    		Service service = this.getDefaultService();
	    		systemLog.setServiceGuid(service.getGuid());
	    		
	    		EventObject systemLogEventObject = new SystemLogEventObj(this);
	    		Map systemLogMap = new HashMap();
	    		systemLogMap.put("systemLog", systemLog);
	    		systemLogMap.put("keyName", "applicationpublish");
	    		systemLogMap.put("node", node);
	    		
	    		systemLogEventObject.setDataMap(systemLogMap);
	    		ContextUtil.getAc().publishEvent(systemLogEventObject);
			} catch (Exception e) {
				log.error(ExceptionUtil.transformException(e));
				status = "2";
			}
			
			ldb.set("success", true);
			ldb.set("status", status);
		}catch(Exception e){
			log.error(ExceptionUtil.transformException(e));
			ldb.set("success", false);
			ldb.set("reason", e.getMessage());
		}
		
		this.json = JSONObject.fromObject(ldb).toString();
		return AJAX;
	}

	public SpecialityManager getSpecialityManager() {
		return specialityManager;
	}

	public void setSpecialityManager(SpecialityManager specialityManager) {
		this.specialityManager = specialityManager;
	}

	public ApplicationManager getApplicationManager() {
		return applicationManager;
	}

	public void setApplicationManager(ApplicationManager applicationManager) {
		this.applicationManager = applicationManager;
	}

	public String getJson_services() {
		return json_services;
	}

	public void setJson_services(String json_services) {
		this.json_services = json_services;
	}
	
	public String getCurrentServiceGuid() {
		return currentServiceGuid;
	}

	public void setCurrentServiceGuid(String currentServiceGuid) {
		this.currentServiceGuid = currentServiceGuid;
	}

	public ServiceManager getServiceManager() {
		return serviceManager;
	}

	public void setServiceManager(ServiceManager serviceManager) {
		this.serviceManager = serviceManager;
	}

	public String getJson_specialities() {
		return json_specialities;
	}

	public void setJson_specialities(String json_specialities) {
		this.json_specialities = json_specialities;
	}

	public String getJson_soTrees() {
		return json_soTrees;
	}

	public void setJson_soTrees(String json_soTrees) {
		this.json_soTrees = json_soTrees;
	}

	public StatisticalObjectTreeManager getStatisticalObjectTreeManager() {
		return statisticalObjectTreeManager;
	}

	public void setStatisticalObjectTreeManager(
			StatisticalObjectTreeManager statisticalObjectTreeManager) {
		this.statisticalObjectTreeManager = statisticalObjectTreeManager;
	}

	public CatalogManager getCatalogManager() {
		return catalogManager;
	}

	public void setCatalogManager(CatalogManager catalogManager) {
		this.catalogManager = catalogManager;
	}

	public SoCollectionManager getSoCollectionManager() {
		return soCollectionManager;
	}

	public void setSoCollectionManager(SoCollectionManager soCollectionManager) {
		this.soCollectionManager = soCollectionManager;
	}

	public Application getAppObj() {
		return appObj;
	}

	public void setAppObj(Application appObj) {
		this.appObj = appObj;
	}

	public String getJson_specialities_filter() {
		return json_specialities_filter;
	}

	public void setJson_specialities_filter(String json_specialities_filter) {
		this.json_specialities_filter = json_specialities_filter;
	}

}
